<template>
  <view class="main-page">
    <!-- 地址区域 -->
    <view class="location-section">
      <view class="location-content">
        <image class="location-icon" src="@/img/车联网服务-00首页_slices/定位2@2x.png"></image>
        <text class="location-text" @click="goToCitySelect">{{ selectedCity || '焦作市山阳区人民路32号' }}</text>
        <image class="refresh-icon" src="@/img/车联网服务-00首页_slices/刷新 (1)@2x.png" @click="refreshLocation"></image>
      </view>
    </view>

    <!-- 功能图标区域 -->
    <view class="function-list">
      <view class="function-item" >
        <image class="function-icon" src="@/img/车联网服务-00首页_slices/car.png"></image>
        <text class="function-text" @click="toMaintenance">车辆维修</text>
      </view>
	  <view class="function-item" @click="toCarMaintennace">
	    <image class="function-icon" src="@/img/车联网服务-00首页_slices/car.png"></image>
        <text class="function-text">汽车保养</text>
      </view>
	  <view class="function-item" @click="goToCleanCar" >
	    <image class="function-icon" src="@/img/车联网服务-00首页_slices/car.png"></image>
        <text class="function-text">专业洗车</text>
      </view>
	  <view class="function-item" >
	    <image class="function-icon" src="@/img/车联网服务-00首页_slices/car.png" @click="tofuel"></image>
        <text class="function-text" @click="tofuel">就近加油</text>
      </view>
    </view>

    <!-- 附近加油站区域 -->
    <view class="station-section">
      <view class="station-title">
        <text class="more1">附近加油站</text>
        <text class="more" @click="goToAllStations">全部</text>
      </view>
      <view id="amapContainer" class="station-map"></view>
    </view>

    <!-- 优惠团购区域 -->
    <view class="group-section">
      <view class="group-title">
        <text class="more1">优惠团购</text>
        <text class="more" @click="goToMoreGroup">更多</text>
      </view>
      <!-- 调试信息 -->
      <view class="debug-info" v-if="groupList.length > 0">
        <text class="debug-text">已加载 {{ groupList.length }} 个团购活动</text>
      </view>
      <view class="group-list">
        <view class="group-item" v-for="(item, index) in groupList" :key="index">
          <image class="group-img" :src="item.img" mode="aspectFill"></image>
          <text class="group-desc">{{ item.desc }}</text>
        </view>
      </view>
    </view>

    <!-- 底部tabbar -->
    <view class="tabbar">
      <view class="tabbar-item" @click="switchTab('home')">
        <image class="tabbar-icon" :src="currentTab === 'home' ? '/static/index2.png' : '/static/index1.png'"></image>
        <text class="tabbar-text" :style="{color: currentTab === 'home' ? activeColor : defaultColor}">首页</text>
      </view>
      <view class="tabbar-item tabbar-middle" @click="switchTab('alarm')">
        <image class="tabbar-icon" src="/static/预警.png"></image>
      </view>
      <view class="tabbar-item" @click="switchTab('mine')">
        <image class="tabbar-icon" :src="currentTab === 'mine' ? '/static/my2.png' : '/static/my1.png'"></image>
        <text class="tabbar-text" :style="{color: currentTab === 'mine' ? activeColor : defaultColor}">我的</text>
      </view>
    </view>
  </view>
</template>

<script>
	import AMapLoader from '@amap/amap-jsapi-loader';
	import { gasStationApi, groupPurchaseApi } from '@/api/index.js';
	
export default {
  data() {
    return {
		selectedCity: '焦作市山阳区人民路32号',
		map: null,
      // 优惠团购数据
      groupList: [],
      // 加油站数据
      gasStations: [],
      // tabbar相关
      currentTab: "home",
      activeColor: "#ff0000",
      defaultColor: "#000000"
    };
  },
  onReady() {
      // 页面渲染完成后初始化地图（需确保容器已存在）
      this.initMap();
      // 加载数据
      this.loadData();
    },
  methods: {
    // 加载页面数据
    async loadData() {
      try {
        // 加载加油站数据
        await this.loadGasStations();
        // 加载团购数据
        await this.loadGroupPurchases();
      } catch (error) {
        console.error('加载数据失败:', error);
      }
    },
    
    // 加载加油站数据
    async loadGasStations() {
      try {
        const response = await gasStationApi.getAllGasStations();
        if (response && response.code === 200 && response.data) {
          this.gasStations = response.data;
          console.log('成功加载加油站数据:', this.gasStations);
        } else {
          console.log('加油站数据加载失败，使用默认数据');
          // 使用默认数据
          this.gasStations = [
            {
              id: 1,
              name: '中国石油焦作山阳加油站',
              address: '焦作市山阳区人民路32号',
              distance: '150m',
              price: '6.12',
              discount: '满200减20'
            },
            {
              id: 2,
              name: '中国石化焦作解放加油站',
              address: '焦作市解放区解放路123号',
              distance: '280m',
              price: '6.08',
              discount: '满300减30'
            }
          ];
        }
      } catch (error) {
        console.error('加载加油站数据失败:', error);
      }
    },
    
    // 加载团购数据
    async loadGroupPurchases() {
      try {
        const response = await groupPurchaseApi.getActiveGroupPurchases();
        if (response && response.code === 200 && response.data) {
          // 转换数据格式，使用数据库中的真实图片，只取前两个
          this.groupList = response.data.slice(0, 2).map(item => ({
            id: item.id,
            img: item.img || "/static/c1.png", // 使用数据库中的img字段
            desc: item.title || item.content || '团购活动'
          }));
          console.log('成功加载团购数据:', this.groupList);
        } else {
          console.log('团购数据加载失败，使用默认数据');
          // 使用默认数据
          this.groupList = [
            {
              id: 1,
              img: "/static/c1.png",
              desc: "汽车保养团购"
            },
            {
              id: 2,
              img: "/static/c2.png",
              desc: "汽车维修团购"
            }
          ];
        }
      } catch (error) {
        console.error('加载团购数据失败:', error);
        // 使用默认数据作为备选
        this.groupList = [
          {
            id: 1,
            img: "/static/c1.png",
            desc: "汽车保养团购"
          },
          {
            id: 2,
            img: "/static/c2.png",
            desc: "汽车维修团购"
          }
        ];
      }
    },
	  toCarMaintennace(){
		  uni.navigateTo({
		  	url:"/pages/carMaintenance/carMaintenance"
		  })
	  },
	  tofuel(){
		  uni.navigateTo({
		  	url:"/pages/Fuel Nearby/Fuel Nearby"
		  })
	  },
	  toMaintenance(){
		uni.navigateTo({
			url:"/pages/vehicleMaintenance/vehicleMaintenance"
		})  
	  },
	goToCleanCar(){
		uni.navigateTo({
		  url: '/pages/cleancar/cleancar'
		})
	},
	goToCitySelect() {
	      uni.navigateTo({
	        url: '/pages/city-select/city-select'
	      })
	    },
	refreshLocation() {
	      this.getLocation();
	      uni.showToast({
	        title: '位置已刷新',
	        icon: 'success'
	      });
	    },
	goToService(type) {
	      // 根据服务类型跳转到对应页面
	      const routes = {
	        repair: '/pages/repair/repair',
	        maintenance: '/pages/maintenance/maintenance',
	        wash: '/pages/wash/wash',
	        gas: '/pages/gas/gas'
	      };
	      
	      if (routes[type]) {
	        uni.navigateTo({
	          url: routes[type]
	        });
	      }
	    },
	   initMap() {
	        // 动态加载高德 API
	        const script = document.createElement('script');
	        script.type = 'text/javascript';
	        script.src = `https://webapi.amap.com/maps?v=2.0&key=f0510425d9c61c040a460360f6af7c20&callback=initAMap`; // 替换为你的Key
	        document.body.appendChild(script);
	  
	        // 定义全局回调函数，初始化地图
	        window.initAMap = () => {
	          this.map = new AMap.Map('amapContainer', {
	            zoom: 13, // 初始缩放级别
	            center: [116.397428, 39.90923] // 初始中心点（北京坐标）
	          });
	  
	          // 可选：添加标记点
	          const marker = new AMap.Marker({
	            position: [116.397428, 39.90923], // 标记点坐标
	            title: '起点'
	          });
	          this.map.add(marker);
	        };
	    },
		onUnload() {
		      // 页面卸载时销毁地图，释放资源
		      if (this.map) {
		        this.map.destroy();
		      }
		      window.initAMap = null; // 清除全局回调
		},
    // 跳转全部加油站页面（示例，可根据实际路由调整）
    goToAllStations() {
      uni.navigateTo({
        url: "/pages/Fuel Nearby/Fuel Nearby"
      });
    },
	
    // 跳转更多团购页面（示例，可根据实际路由调整）
    goToMoreGroup() {
      uni.navigateTo({
        url: "/pages/GroupBuy/GroupBuy"
      });
    },
    
    // 跳转团购详情页面
    goToGroupDetail(item) {
      uni.navigateTo({
        url: `/pages/groupDetail/groupDetail?item=${JSON.stringify(item)}`
      });
    },
    
    // tabbar切换
    switchTab(tab) {
      this.currentTab = tab;
      // 可根据tab类型，进行页面跳转或数据加载等操作，这里简单演示切换样式
      if (tab === "home") {
        // 首页逻辑
      } else if (tab === "alarm") {
		  uni.navigateTo({
		    url: "/pages/emergency-rescue/emergency-rescue"
		  });
      } else if (tab === "mine") {
        // 我的页逻辑
        uni.navigateTo({
          url: "/pages/personalCenter/personalCenter"
        });
      }
    },
  },
  onShow() {
      // 页面显示时检查是否有选中的城市
      if (this.selectedCity) {
        console.log(`当前城市：${this.selectedCity}`);
      }
    }
  
};
</script>

<style scoped>
.main-page {
  background-color: #fff;
  min-height: 100vh;
  position: relative;
}

/* 状态栏 */
.status-bar {
  height: 44rpx;
  background-color: #fff;
}

/* 顶部导航栏 */
.header-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  height: 88rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.iconfont {
  font-size: 40rpx;
  color: #666;
}

/* 地址区域 */
.location-section {
  padding: 20rpx 30rpx;
  background-color: #fff;
}

.location-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.location-icon {
  width: 28rpx;
  height: 28rpx;
  margin-right: 15rpx;
}

.location-text {
  flex: 1;
  font-size: 24rpx;
  color: #333;
}

.refresh-icon {
  width: 30rpx;
  height: 30rpx;
  margin-left: 20rpx;
}

/* 功能图标区域 */
.function-list {
  display: flex;
  justify-content: space-around;
  padding: 20rpx 20rpx;
  background-color: #fff;
}

.function-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 150rpx;
}

.function-icon-container {
  width: 120rpx;
  height: 120rpx;
  background-color: #f8f9fa;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15rpx;
}

.function-icon {
  width: 60rpx;
  height: 60rpx;
}

.function-text {
  font-size: 24rpx;
  color: #333;
  text-align: center;
}

/* 加油站区域 */
.more1{
	font-size: 28rpx;
	font-weight: bold;
}
.more {
  font-size: 26rpx;
  color: #007aff;
}
.station-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}
.station-section {
  margin-top: 1rpx;
  background-color: #fff;
  padding: 30rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.more-btn {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.more-text {
  font-size: 28rpx;
  color: #666;
}

.map-container {
  border-radius: 15rpx;
  overflow: hidden;
}

.station-map {
  width: 100%;
  height: 450rpx;
}

/* 团购区域 */
.group-section {
  margin-top: 1rpx;
  background-color: #fff;
  padding: 30rpx;
}

.group-list {
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
}
.group-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}
.group-item {
  flex: 1;
  background-color: #f8f9fa;
  border-radius: 15rpx;
  overflow: hidden;
}

.group-img {
  width: 100%;
  height: 200rpx;
  background-color: #e9ecef;
  object-fit: cover;
}

.group-desc {
  font-size: 26rpx;
  color: #333;
  padding: 15rpx;
  text-align: center;
  line-height: 1.4;
}

/* 调试信息 */
.debug-info {
  margin-bottom: 15rpx;
  padding: 10rpx 20rpx;
  background-color: #f0f0f0;
  border-radius: 10rpx;
  text-align: center;
}

.debug-text {
  font-size: 24rpx;
  color: #666;
}

/* 底部导航栏 */
.tabbar {
  display: flex;
  justify-content: space-around;
  align-items: center;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 120rpx;
  background-color: #fff;
  border-top: 1rpx solid #f0f0f0;
  padding-bottom: 20rpx;
}

.tabbar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
}

.tabbar-middle {
  position: relative;
  top: -30rpx;
}

.alarm-button {
  width: 100rpx;
  height: 100rpx;
  background-color: #ff4444;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(255, 68, 68, 0.3);
}

.alarm-icon {
  width: 50rpx;
  height: 50rpx;
}

.tabbar-icon {
  width: 50rpx;
  height: 50rpx;
  margin-bottom: 8rpx;
}

.tabbar-text {
  font-size: 24rpx;
  color: #333;
}
</style>
